const router = require('koa-router')();
const {
    resBody,
    md5,
} = require("../../utils")
const {
    models,
    sequelize
} = require('../../utils/db');
const {
    getJwtToken,
    getJwtInfo
} = require('../../utils/jwtToken');

// 用户登陆
router.post('/login', async (ctx, next) => {
    const {
        phone,
        password,
    } = ctx.request.body;
    if (!phone ||
        !password) {
        throw (resBody.paramError)
    }
    const userInfo = await models.admin_model.findOne({
        where: {
            phone
        }
    });
    const {
        id,
        name,
        type,
        password: dbsPassword
    } = userInfo;
    console.log(userInfo);
    if (dbsPassword !== md5(password)) {
        throw (resBody.passWordErr);
    }
    const token = getJwtToken({
        id,
        name,
        type,
        phone,
    });
    ctx.body = {
        ...resBody.success,
        msg: '登陆成功！',
        data: {
            id,
            name,
            type,
            phone,
            token
        }
    };
})

// 验证用户登录
router.post('/checkLogin', async (ctx, next) => {
    const {
        token
    } = ctx.request.body;
    const {
        id,
        name,
        type,
        phone
    } = getJwtInfo(token);
    ctx.body = {
        ...resBody.success,
        data: {
            name,
            type,
            phone,
            token,
        }
    };
})

module.exports = router